package com.strongbj.iot.devices.newlight.response.handle;

import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.strongbj.core.message.MessageHandleContext;
import com.strongbj.core.util.ByteUtil;
import com.strongbj.core.util.ContextUtils;
import com.strongbj.iot.devices.newlight.common.NetMapping;
import com.strongbj.iot.devices.newlight.entity.T;
import com.strongbj.iot.devices.newlight.message.NewLightMQMessage;
import com.strongbj.iot.devices.newlight.message.NewLightReaderMessage;
import com.strongbj.iot.mq.producer.TopicSender;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class NewLightReaderResponseHandleContext extends SimpleChannelInboundHandler<NewLightReaderMessage> {
	private TopicSender topicSender = (TopicSender) ContextUtils.getBean("topicSender");
	private MessageHandleContext<NewLightReaderMessage, Object> messageHandleContent;

	private static Logger logger = LogManager.getLogger(NewLightReaderResponseHandleContext.class.getName());

	public NewLightReaderResponseHandleContext() {
		super();
		this.messageHandleContent = new MessageHandleContext<>();
//		this.messageHandleContent.addHandleClass(new LableSignalTestResponseHandle());
		this.messageHandleContent.addHandleClass(new LabelBindingResponseHandle());
		this.messageHandleContent.addHandleClass(new TagLedControlResponseHandle());
		this.messageHandleContent.addHandleClass(new RangeTagLedControlResponseHandle());
		this.messageHandleContent.addHandleClass(new MultiLabelLedControlResponseHandle());
		this.messageHandleContent.addHandleClass(new SingleInventoryResponseHandle());
		this.messageHandleContent.addHandleClass(new InventoryResponseHandle());
//		this.messageHandleContent.addHandleClass(new ChannelStateApplyResponseHandle());
//		this.messageHandleContent.addHandleClass(new ChannelDisposibleResponseHandle());
		this.messageHandleContent.addHandleClass(new ChannelHandle());
		this.messageHandleContent.addHandleClass(new LowBatteryResponseHandle());
		this.messageHandleContent.addHandleClass(new ButtonResponseHandle());
		this.messageHandleContent.addHandleClass(new TagLoseResponseHandle());
		this.messageHandleContent.addHandleClass(new HeartbeatResponseHandle());
		this.messageHandleContent.addHandleClass(new AutoInventoryCtrlResponseHandle());
		this.messageHandleContent.addHandleClass(new UnBindTagReturnHandle());
		this.messageHandleContent.addHandleClass(new ReBindTagHandle());
		this.messageHandleContent.addHandleClass(new TagAccessRequestHandle());
		this.messageHandleContent.addHandleClass(new TagInfoHandle());
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
		String hostname = insocket.getAddress().getHostAddress();
		logger.info("新点亮Reader已连接 {}:{}", hostname,insocket.getPort());
		try {
			NetMapping.getInstance().addChannel(ctx.channel());
			NetMapping.getInstance().addChannelMapping(hostname, ctx.channel());
		} catch (Exception e) {
			logger.error("", e);
		}
//		{
//			"actionCode": "unbindTag",
//			"postdata": {
//				"readerCode": "163.0.5",
//				"tags": ["180.0.123.15"]
//			},
//			"guid":"214234T3YT"
//		}
//		new Timer().schedule(new TimerTask() {
//int index=0;
//			@Override
//			public void run() {
//				while(index++<10) {
//				// TODO Auto-generated method stub
//				NewLightMQMessage mes = new NewLightMQMessage();
//				mes.setActioncode("activeTag");
//				mes.setGUID(ByteUtil.byteArrToHexString(T.getTimeStamp()));
//				Map<String,Object> map = new HashMap<>();
//				map.put("readerCode", "163.0.10");
//				List<String> tags = new ArrayList<>();
//				tags.add("180.0.122.147");
//				map.put("readerCode", "163.0.5");
//				map.put("tags", tags);
//				map.put("led1", true);
//				map.put("led1", false);
//				map.put("led1", false);
//				map.put("led1", false);
//				map.put("ledState", "light");
//				mes.setPostdata(map);
//				String json = JSON.toJSONString(mes);
//				topicSender.send("wh.reader.command.request", json);
//				}
//			}
//			
//		},2000,1000);
		super.channelActive(ctx);
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
		String hostname = insocket.getAddress().getHostAddress();
		logger.info("新点亮Reader已断开 {}", hostname);
		try {
			NetMapping.getInstance().removeChannel(ctx.channel());
			NetMapping.getInstance().removeChannelMapping(hostname);
		} catch (Exception e) {
			logger.error("", e);
		}
		
		this.messageHandleContent.destory();
		this.messageHandleContent.clearHandleClass();
		super.channelInactive(ctx);
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, NewLightReaderMessage msg) throws Exception {
		if (msg == null)
			return;
		// logger.info("收到Reader数据信息，数据类型："+msg.getType()+" 设备编号："+msg.getAddress()+"
		// 数据位："+ByteUtil.byteArrToHexString(msg.getBody()));
		this.messageHandleContent.handle(ctx, msg);
	}
}
